package com.xyb.controller;


import cn.hutool.http.HttpUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@CrossOrigin
@RestController
@RequestMapping("github")
public class GithubController {
    // Github授权的客户端id
    private static String clientId = "6ad59df85dbd8fea4c75";
    // Github授权的客户端密钥
    private static String clientSecret = "34794a6462e53a9e99708e951e672c77c95cf998";
    // Github接收我们请求之后,重定向的URL
    private static String redirectUrl = "http://127.0.0.1:8888/p4java/login-web/github/code";
    // Github认证服务器地址
    private static String authUrl = "https://github.com/login/oauth/authorize";
    // Github认证服务器 token 授权地址
    private static String tokenUrl = "https://github.com/login/oauth/access_token";

    @GetMapping("url")
    public String oauth2(HttpServletResponse response) throws IOException {
        String state = "HelloWorld";
        StringBuilder sb = new StringBuilder();
        sb.append(authUrl).append("?")
                .append("response_type").append("=").append("code")
                .append("&")
                .append("client_id").append("=").append(clientId)
                .append("&")
                .append("redirect_uri").append("=").append(redirectUrl)
                .append("&")
                .append("state").append("=").append(state);

        // 拼接的 URL 为   https://github.com/login/oauth/authorize  ?  response_type=code  &  client_id=你的客户端id  &  redirect_uri=你自定义的重定向URL  &  state=你自定义的内容
        String url = sb.toString();
        return url;
    }

    @GetMapping("code")
    public void code(String code,String state) throws IOException {
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        /**
         * 使用该 code 请求令牌
         */
        HashMap<String, Object> paramMap = new HashMap<>();
        {
            paramMap.put("client_id",clientId);
            paramMap.put("client_secret",clientSecret);
            paramMap.put("code",code);
        }

        String respBody = HttpUtil.post(tokenUrl, paramMap);
        System.out.println("respBody = " + respBody);

        //解析 access_token  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

        String[] split = respBody.split("&");
        String[] split1 = split[0].split("=");
        String access_token = split1[1];

        System.out.println("access_token = " + access_token);

        HashMap<String, Object> paramMap1 = new HashMap<>();
        {
            paramMap1.put("Authorization","bearer " + access_token);
            paramMap1.put("Accept","application/vnd.github.v3+json");
        }
        String s = HttpUtil.get("https://api.github.com/user");
        System.out.println("s = " + s);
    }
}
